<!-- dataTables -->
<link href="http://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"/>
<link href="/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet"/>

<!-- NProgress -->
<link href="/vendors/nprogress/nprogress.css" rel="stylesheet">
<!-- 上传图片 -->
<link href="/vendors/fileinput/fileinput.min.css" rel="stylesheet">


<!-- page content -->
<div id="moduleDiv" class="right_col" role="main">
    <div class="">
        <div class="page-title">
            <div class="title_left">
                <h3>Users <small>List</small></h3>
            </div>
        </div>

        <div class="clearfix"></div>

        <div class="row">
            <div class="col-md-12 col-sm-12">
                <div class="x_panel">
                    <div class="x_title">
                        <button
                                class="btn btn-sm btn-primary"
                                type="button"
                                @click="initModuleAdd()"
                                data-toggle="modal"
                                data-target="#moduleAdd"
                        >
                            新增
                        </button>
                        <ul class="nav navbar-right panel_toolbox">
                            <li>
                                <a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                            </li>
                            <li class="dropdown">
                                <a
                                        href="#"
                                        class="dropdown-toggle"
                                        data-toggle="dropdown"
                                        role="button"
                                        aria-expanded="false"
                                ><i class="fa fa-wrench"></i
                                ></a>
                                <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                    <a class="dropdown-item" href="#">Settings 1</a>
                                    <a class="dropdown-item" href="#">Settings 2</a>
                                </div>
                            </li>
                            <li>
                                <a class="close-link"><i class="fa fa-close"></i></a>
                            </li>
                        </ul>
                        <div class="clearfix"></div>
                    </div>
                    <div class="x_content">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="card-box table-responsive">
                                    <table
                                            id="moduleTable"
                                            class="table table-striped table-bordered"
                                            style="width: 100%"
                                    >
                                        <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>UserName</th>
                                            <th>Password</th>
                                            <th>CreateDate</th>
                                            <th>Opration</th>
                                        </tr>
                                        </thead>

                                        <tbody></tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div th:replace="account/userAdd"></div>
    <div th:replace="account/userEdit"></div>
</div>

<!-- Datatables -->
<script src="/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>

<!-- NProgress -->
<script src="/vendors/nprogress/nprogress.js" type="text/javascript"></script>
<!-- morris.js -->
<script src="/vendors/raphael/raphael.min.js" type="text/javascript"></script>
<script src="/vendors/morris.js/morris.min.js" type="text/javascript"></script>
<!-- bootstrap-progressbar -->
<script src="/vendors/bootstrap-progressbar/bootstrap-progressbar.min.js" type="text/javascript"></script>
<!-- 上传图片 -->
<script src="/vendors/fileinput/fileinput.min.js" type="text/javascript"></script>


<script>
    var usersVue = new Vue({
        el: "#moduleDiv",
        data: {
            // 表格的数据结构
            tableData: {
                draw: 0,
                recordsTotal: 0,
                recordsFiltered: 0,
                data: [],
            },
            pageSize: 5,
            model: {
                userName: "",
                password: "",
                roles: [],
                userImage:""
            },
            allRoles: [],
            dataTable: []
        },
        methods: {
            // 行数据结构
            rowData: function (id, userName, password, createDate) {
                var module = {};
                module.id = id;
                module.userName = userName;
                module.password = password;
                module.createDate = createDate;
                module.operate = function () {
                    return (
                        "<a href='#' class='btn_editcolor' data-toggle='modal' data-target='#moduleEdit' " +
                        "onclick='initEditModule(\"" +
                        id +
                        "\")'><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" fill=\"currentColor\" class=\"bi bi-pencil\" viewBox=\"0 0 16 16\">\n" +
                        "  <path d=\"M12.146.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12.5V12h-.5a.5.5 0 0 1-.5-.5V11h-.5a.5.5 0 0 1-.468-.325z\"/>\n" +
                        "</svg></a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
                        "<a href='#;' onclick='deleteModule(\"" +
                        id +
                        "\")' class='btn_editcolor'><svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" fill=\"currentColor\" class=\"bi bi-trash\" viewBox=\"0 0 16 16\">\n" +
                        "  <path d=\"M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z\"/>\n" +
                        "  <path fill-rule=\"evenodd\" d=\"M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z\"/>\n" +
                        "</svg></a>"
                    );
                };
                return module;
            },
            // 初始化表格数据
            initTableData: function () {
                var self = this;
                this.dataTable = $("#moduleTable").DataTable({
                    paging: true, //分页
                    serverSide: true, //开启后端分页
                    pagingType: "full_numbers", //分页样式的类型simple/simple_numbers/full/full_numbers
                    pageLength: self.pageSize, //定义初始的页长
                    processing: true,
                    destroy: true, //允许销毁替换，在表格重新查询时，可以自动销毁以前的data
                    lengthChange: true, //控制是否能够调整每页的条数
                    searching: true,
                    "data-show-refresh": true,
                    ordering: true,
                    autoWidth: false,
                    ajax: function (data, callback, settings) {
                        // 从data获取查询数据
                        var columIndex = data.order[0].column;
                        var direction = data.order[0].dir;
                        var sort = data.columns[columIndex].name;
                        pageSize = data.length == undefined ? pageSize : data.length;

                        var search = {};
                        search.currentPage = data.start / pageSize + 1;
                        search.pageSize = pageSize;
                        search.sort = sort;
                        search.direction = direction;
                        search.keyword = data.search.value;

                        $.ajax({
                            url: "/api/users",
                            type: "post",
                            contentType: "application/json",
                            data: JSON.stringify(search),
                            success: function (rs) {
                                // 拿到结果集做判断
                                if (!rs) {
                                    layer.alert("请求出错，请稍后重试" + rs.errmsg, {icon: 2});
                                    callback(self.tableData);
                                    return;
                                }
                                if (rs.list == null) {
                                    $("#moduleTable tbody tr").remove();
                                    $("#loading").remove();
                                    callback(self.tableData);
                                    return;
                                }

                                $("#loading").remove();

                                // 封装数据
                                var rowsData = [];
                                for (var i = 0; i < rs.list.length; i++) {
                                    //包装行数据
                                    var rowData = self.rowData(
                                        rs.list[i].id,
                                        rs.list[i].userName,
                                        rs.list[i].password,
                                        rs.list[i].createDate
                                    );

                                    // 将行数据放到数组里
                                    rowsData.push(rowData);
                                }
                                self.tableData.data = rowsData;
                                self.tableData.recordsTotal = rs.total;
                                self.tableData.recordsFiltered = rs.total;
                                callback(self.tableData);
                            },
                            error: function (data) {
                                layer.alert(data.responseText, {icon: 0});
                            },
                        });
                    },
                    columns: [
                        //定义行数据字段
                        {data: "id", name: "id", sortable: true},
                        {data: "userName", name: "user_name", sortable: true},
                        {data: "password", name: "password", sortable: true},
                        {data: "createDate", name: "create_date", sortable: true},
                        {data: "operate", width: "80px", sortable: false},
                    ],
                });
            },
            initModuleAdd: function () {
                this.model = {
                    userName: "",
                    password: "",
                    roles: [],
                    userImage:""
                };
            },
            addModule: function () {
                this.model.roles = this.model.roles.map((item) => {
                    var role = {};
                    role.id = item;
                    return role;
                });
                console.log(this.model);

                if (this.model.userName == "" || this.model.password == "") {
                    layer.alert("请输入用户名和密码。", {icon: 2});
                    return;
                }

                var self = this;
                $.ajax({
                    url: "/api/user",
                    type: "post",
                    contentType: "application/json",
                    data: JSON.stringify(self.model),
                    success: function (result) {
                        if (result.status == 200) {
                            $("#moduleAdd").modal("hide");
                            self.initTableData();
                        } else {
                            layer.alert(result.message, {icon: 2});
                        }
                    },
                    error: function (errorMsg) {
                        layer.alert(errorMsg.responseText, {icon: 2});
                    },
                });
            },
            initAllRoles: function () {
                var self = this;
                $.ajax({
                    url: "/api/roles",
                    type: "get",
                    success: function (result) {
                        self.allRoles = result;
                    },
                    error: function (errorMsg) {
                        layer.alert(errorMsg.responseText, {icon: 2});
                    },
                });
            },
            initEditModule: function (id) {
                var self = this;
                $.ajax({
                    url: "/api/user/" + id,
                    type: "get",
                    success: function (result) {
                        result.roles = result.roles.map((item) => {
                            return item.id;
                        });
                        self.model = result;
                    },
                    error: function (errorMsg) {
                        layer.alert(errorMsg.responseText, {icon: 2});
                    },
                });
            },
            editModule: function () {
                if (this.model.userName == "" || this.model.password == "") {
                    layer.alert("Please input user name and password!", {icon: 2});
                    return;
                }
                this.model.roles = this.model.roles.map(item => {
                    var role = {};
                    role.id = item;
                    return role;
                });
                var self = this;
                $.ajax({
                    url: "/api/user",
                    type: "put",
                    contentType: "application/json",
                    data: JSON.stringify(self.model),
                    success: function (result) {
                        if (result.status == 200) {
                            $("#moduleEdit").modal("hide");
                            // 重新绘制表格，页面不变更
                            self.dataTable.draw(false);
                        } else {
                            layer.alert(result.message, {icon: 2});
                        }
                    },
                    error: function (errorMsg) {
                        layer.alert(errorMsg.responseText, {icon: 2});
                    },
                });
            },
            deleteModule: function (id) {
                var self = this;
                bootbox.confirm("Are you sure?", function (result) {
                    if (result) {
                        $.ajax({
                            url: "/api/user/" + id,
                            type: "delete",
                            success: function (rs) {
                                if (rs.status == 200) {
                                    self.initTableData();
                                } else {
                                    layer.alert(rs.message, {icon: 0});
                                }
                            },
                            error: function (data) {
                                layer.alert(data.responseText, {icon: 0});
                            },
                        });
                    }
                });
            },
            initFileInput: function () {
                var self = this;
                $("#imageUpload")
                    .fileinput({
                        uploadUrl: "/api/image/profileBig",
                        enctype: "multipart/form-data",
                        previewFileType: "image",
                        uploadAsync: true,
                        allowedFileExtensions: ["png", "jpg", "jpeg", "ico", "bmp", "gif"],
                        maxFileCount: 1,
                        maxFileSize: 3072,
                        minImageWidth: 50,
                        minImageHeight: 50,
                        maxImageWidth: 1000,
                        maxImageHeight: 1000,
                        msgFilesTooMany: "Upload file count({n} - {m})",
                        showCaption: false,
                        dropZoneEnabled: false,
                        showBrowse: true,
                        browseClass: "btn btn-primary",
                        uploadClass: "btn btn-info",
                        removeClass: "btn btn-danger",
                    })
                    .on("fileerror", function (event, data, msg) {
                        layer.alert("Upload file failed" + msg, { icon: 0 });
                    })
                    .on("fileuploaded", function (event, data) {
                        if (data.response.status == 200) {
                            self.model.userImage = data.response.data;
                        } else {
                            $(".fileinput-remove-button").click();
                        }
                        layer.alert(data.response.message, { icon: 0 });
                    })
                    .on("fileclear", function (event) {});
            },
        },
        created() {
            window.initEditModule = this.initEditModule;
            window.deleteModule = this.deleteModule;
        },
        mounted() {
            this.initTableData();
            this.initAllRoles();
            this.initFileInput();
        },
    });
</script>
